package com.amoby.main.action.business;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amoby.base.common.BaseAction;
import com.amoby.base.common.Constants;
import com.amoby.base.common.Pager;
import com.amoby.base.utils.DateUtil;
import com.amoby.base.utils.alipay.AlipayNotify;
import com.amoby.main.entity.AlipayOrder;
import com.amoby.main.entity.Business;
import com.amoby.main.entity.Customer;
import com.amoby.main.entity.PushSmsLog;
import com.amoby.main.mapper.AlipayMapper;
import com.amoby.main.mapper.AlipayOrderMapper;
import com.amoby.main.mapper.BusinessMapper;
import com.amoby.main.mapper.CustomerMapper;
import com.amoby.main.mapper.PushSmsLogMapper;
import com.amoby.main.service.AlipayService;
import com.amoby.main.service.AreaService;
import com.amoby.main.service.BusinessService;
import com.amoby.main.service.BusinessTypeService;
import com.amoby.main.service.PushSmsService;
import com.google.common.collect.Maps;

/**
 * ParamAction Desc：支付宝商户管理
 * @address http://www.yingmob.com/
 * @author zhaoyy
 * @date 2016年4月11日 上午10:44:37
 */
@Controller
public class AlipayAction extends BaseAction {
    @Autowired
    private BusinessService     businessService;
    @Autowired
    private BusinessTypeService businessTypeService;
    @Autowired
    private AreaService         areaService;
    @Autowired
    private AlipayService       alipayService;
    @Autowired
    private AlipayMapper        alipayMapper;
    @Autowired
    private BusinessMapper      businessMapper;
    @Autowired
    AlipayOrderMapper           alipayOrderMapper;
    @Autowired
    private PushSmsService      pushSmsService;
    @Autowired
    private PushSmsLogMapper    pushSmsLogMapper;
    @Autowired
    private CustomerMapper      customerMapper;


    /**
     * 初始化时间
     * @author Lasing 2016-6-3 上午10:55:32
     * @param binder
     * @throws Exception
     */
    @InitBinder
    protected void init(WebDataBinder binder) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    /**
     * 初始化页面
     * @author Lasing 2016-6-3 上午10:55:40
     * @return
     */
    @RequestMapping(value = "/menus/alipay_mgr.html", method = RequestMethod.GET)
    public String listPage(ModelMap model) {
     // 商户类型父类型
        model.put("shopType", businessTypeService.queryParent());
        model.put("areas", areaService.queryParent());
        return AD_HTML + "business/alipay_mgr";
    }


    /**
     * 商户分页查询
     * @author Lasing 2016-6-3 上午10:56:44
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/alipay/list.html", method = RequestMethod.POST)
    public Object list(HttpServletRequest request) {
        Pager pager = createPager(request);
        pager.addParam("startDate", getRequestParams(String.class, request, "startDate"));
        pager.addParam("endDate", getRequestParams(String.class, request, "endDate"));
        pager.addParam("username", getRequestParams(String.class, request, "username"));
        pager.addParam("shopName", getRequestParams(String.class, request, "shopName"));
        pager.addParam("channelName", getRequestParams(String.class, request, "channelName"));
        pager.addParam("id", getRequestParams(String.class, request, "id"));
        pager.addParam("status", getRequestParams(String.class, request, "status"));
        pager.addParam("shopStatus", getRequestParams(Integer.class, request, "shopStatus"));
        pager.addParam("discount", getRequestParams(Integer.class, request, "discount"));
        pager.addParam("shopType", getRequestParams(Integer.class, request, "shopType"));
        pager.addParam("shopSubclass", getRequestParams(Integer.class, request, "shopSubclass"));
        pager.addParam("shopArea", getRequestParams(Integer.class, request, "shopArea"));
        pager.addParam("payEnable", getRequestParams(Integer.class, request, "payEnable"));
        pager.addParam("isBrokerage", getRequestParams(Integer.class, request, "isBrokerage"));
        pager = businessService.query(pager);
        return getGridData(pager);
    }

    /**
     * 生成二维码
     */
    @ResponseBody
    @RequestMapping(value = "/alipay/crqrcode.do")
    public Object qrcode(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = Maps.newHashMap();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        String merchantId = getRequestParams(String.class, request, "id");
        String merchantName = getRequestParams(String.class, request, "shopName");
        params = alipayService.createAlipayCode(merchantId, merchantName);
        logger.debug("成功二维码返回结果数据==============="+params);
        if(params!=null &&"success".equals(params.get("result"))){
            Business business = businessService.findById(Long.parseLong(merchantId));
            resultMap.put(RESULT, "true");
            resultMap.put(MESSAGE, params.get("message"));
            resultMap.put("qrcodeurl", business.getQrcodeurl());
        }else{
          resultMap.put(RESULT, "fail");
          resultMap.put(MESSAGE, params.get("message"));
        }
        return resultMap;
    }
   
    /*@RequestMapping(value = "/robots.txt")
    public void robots(HttpServletResponse response, HttpServletRequest request, ModelMap model) {
       // response.setContentType("text/plain; charset=UTF-8");
        try {
            String ro ="User-agent: Baiduspider\nDisallow: /";
            response.getWriter().write(ro);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    
    //====================================================================支付宝支付回调=================================================================
    /**
     * 支付宝活动，支付宝扫码支付回调
     * @param request
     * @param response
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/alipay.hdcall")
    public void hdcall(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = getRequestParams(request);
        logger.debug("支付宝用户扫码澳新通商家付款==alipay=params==" + params.toString());
        // params.put("subject", "%E5%BB%96%E6%B1%9F%E7%BA%A2");
        if (AlipayNotify.verifyAlipayOrder(params)) {// 验证成功
            // 澳新通商家，用户支付宝扫码付款===生成对应澳新通订单订单进行处理
            logger.debug("==alipay=vlidate success==" + params);
            alipayMapper.insertRecord(params);// 保存支付宝回调记录
            Map<String, Object> alipayRecord = alipayMapper.getAlipayRecord(params.get("notify_id"));
            logger.debug("判断支付宝回调=========="+alipayRecord.get("status") != null && "0".equals(alipayRecord.get("status").toString()));
            if (alipayRecord.get("status") != null && "0".equals(alipayRecord.get("status").toString())) {// 避免支付宝重复回调导致重复处理订单
                // 根据二维码信息查询商家信息
                logger.debug("避免支付宝重复回调导致重复处理订单========================");
                String extra_common_param = params.get("extra_common_param");
                Map map = (Map) JSONObject.fromObject(extra_common_param);
                String qrcode = map.get("qrcode").toString();// 商家二维码("https://qr.alipay.com/ocx03434jxbkvtbh0ek5474)
                qrcode = qrcode.substring(qrcode.lastIndexOf("/") + 1);
                Business bussiness = businessMapper.selectBusinessByQrcode(qrcode);
                AlipayOrder ao = new AlipayOrder();
                // 生成澳新通订单好规则 二维码末尾两位+随机两位数+时间搓+随机三位数
                ao.setOrderNo(bussiness.getUsername().substring(bussiness.getUsername().length() - 2).toUpperCase()
                        + StringUtils.leftPad(new Random().nextInt(99) + "", 2, "2") + System.currentTimeMillis()
                        + StringUtils.leftPad(new Random().nextInt(999) + "", 3, "8"));
                ao.setAmount(Double.valueOf(params.get("trans_amount")));// 支付宝标价交易总金额（该笔订单的标价总金额。若标价金额为外币，则为外币标价金额。如果标价为人民币下单，不返回该参数。）
                ao.setBsId(bussiness.getId());
                ao.setBsName(bussiness.getShopName());
                ao.setBsType("00" + bussiness.getShopType());
                ao.setBrokerage(new BigDecimal(ao.getAmount().toString()).multiply(new BigDecimal(bussiness.getBrokerage().toString()))
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());// 当前的佣金
                // 创单时间
                ao.setCrtime(DateUtil.getCurDate());
                ao.setPayType((byte) 1);// 默认支付宝
                ao.setTransferStatus((byte) 0);// 默认未转账
                ao.setRefundStatus((byte) 0);// 未申请退款，默认
                ao.setState((byte) 1);// 默认已支付
                // ao.setToken();//改为非服务窗流程后取消该字段
                ao.setUptime(DateUtil.getCurDate());
                ao.setTradeNo(params.get("trade_no"));// 支付宝交易号
                ao.setBuyer(params.get("buyer_email"));// 买家支付宝账号
                ao.setPayTime(DateUtil.paseDatetime(params.get("gmt_payment")));// 交易付款时间
                logger.debug("保存支付宝订单===============================");
                alipayOrderMapper.insertSelective(ao);
                //判断是否是新增支付宝账号=======================================
                Map<String, Object> mapint = new HashMap<String, Object>();
                mapint.put("customer", params.get("buyer_email"));
                mapint.put("bsid", bussiness.getId());
                Customer customer = customerMapper.selectCustomerByBuyer(mapint);
                if(customer==null){ //如果不存在则保存
                    Customer comer = new Customer();
                    comer.setCustomer(params.get("buyer_email"));
                    comer.setSource(1);
                    comer.setBsid(bussiness.getId().intValue());
                    comer.setCrtime(DateUtil.paseDatetime(params.get("gmt_payment")));
                    customerMapper.insertSelective(comer);
                }
              //判断是否是新增支付宝账号=============结束==========================
                alipayMapper.processAlipayRecord(params);
                Business business = businessMapper.selectByPrimaryKey(ao.getBsId());
                if (business != null) {
                    /** 向商家发送短信 */
                    String code = ao.getOrderNo().substring(ao.getOrderNo().length() - 4);// 验证码
                    Double amount = ao.getAmount();// 消费金额
                    /** 推送app消息通知app发短信给商户 */
                    if (business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())&& business.getShopName() != null) {
                        PushSmsLog smslog = new PushSmsLog();
                        smslog.setOrderNo(ao.getOrderNo());    //订单号
                        smslog.setPayTime(ao.getPayTime());    //消费时间
                        smslog.setDealpushSendTime(DateUtil.getCurDate());  //交易短信推送时间
                        smslog.setPushdCount(1);      //交易推送数量
                        pushSmsLogMapper.insertSelective(smslog);    //保存推送短信日志
                        String content = "[" + code + "]" + " The payment amount of $" + amount
                                + " has been processed successfully http://mmobile.supaytech.com.au/ ." + Constants.SMS_LAST_STR;
                        StringBuffer sb = new StringBuffer(business.getPhone2()+"");
                        String sendPhone = "";
                        if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                            sb.append("|").append(business.getPhone3());
                            if (StringUtils.isNotEmpty(business.getPhone4())) {
                                sb.append("|").append(business.getPhone4());
                            }
                            if (StringUtils.isNotEmpty(business.getPhone5())) {
                                sb.append("|").append(business.getPhone5());
                            }
                        }
                        sendPhone = sb.toString();
                        logger.debug("交易第一次需要推送的号码===="+sendPhone);
                        pushSmsService.smspush(sendPhone, ao.getOrderNo(),content,1);
                    }
                }
                response.getWriter().write("success");
            } else {// 重复回调了
                response.getWriter().write("success");
            }
        } else {// 验证失败
            logger.debug("==alipay=vlidate fail==" + params);
            response.getWriter().write("fail");
        }
    }

    /**
     * 将Request中的参数转为map
     * @throws UnsupportedEncodingException
     */
    private Map<String, String> getRequestParams(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = URLDecoder.decode(valueStr, "GBK");
            params.put(name, valueStr);
        }
        return params;
    }
}
